package dbops

import (
	"edgex_back_management/model"
	. "gopkg.in/mgo.v2/bson"
)

// ttl: time to live
func SaveSession(sessionId string, ttl int64, userName string) error {
	store := DS.DataStore()
	defer store.S.Close()

	session := model.Session{Id: sessionId, UserName: userName, TTL: ttl}

	c := store.S.DB("edgex-club").C("session")
	err := c.Insert(session)
	if err != nil {
		return err
	}

	return nil
}

func FindOneSessionById(sessionId string) (*model.Session, error) {
	store := DS.DataStore()
	c := store.S.DB("edgex-club").C("session")
	defer store.S.Close()

	session := new(model.Session)
	err := c.FindId(sessionId).One(&session)
	if err != nil {
		return nil, err
	}

	return session, nil
}

func FindOneSessionByName(userName string) (*model.Session, error) {
	store := DS.DataStore()
	c := store.S.DB("edgex-club").C("session")
	defer store.S.Close()

	session := new(model.Session)
	err := c.Find(M{"userName": userName}).One(&session)
	if err != nil {
		return nil, err
	}

	return session, nil
}

func FindAllSession() ([]model.Session, error) {
	store := DS.DataStore()
	c := store.S.DB("edgex-club").C("session")
	defer store.S.Close()

	sessions := make([]model.Session, 16)
	err := c.Find(nil).All(&sessions)
	if err != nil {
		return nil, err
	}

	return sessions, nil
}

func DeleteOneSession(sessionId string) error {
	store := DS.DataStore()
	c := store.S.DB("edgex-club").C("session")
	defer store.S.Close()

	err := c.Remove(M{"_id": sessionId})
	if err != nil {
		return err
	}
	return nil
}
